﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using AForge.Video.DirectShow;
using AForge.Video;
using System.Threading;
using System.Reflection;
using System.Diagnostics;

namespace WebCamKezelesV1._0
{
    public partial class Form1 : Form
    {
        VideoCaptureDevice video;
        Point koordinata=new Point(0,0);
        int talalatok = 0;
        float Href, Sref;
        
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            video = new VideoCaptureDevice(new FilterInfoCollection(FilterCategory.VideoInputDevice)[0].MonikerString);
            video.DesiredFrameSize = new System.Drawing.Size(160, 120);
            OpenVideoSource(video);
        }

        private void OpenVideoSource(IVideoSource source) 
        {
            // start new video source
            videoSourcePlayer.VideoSource = new AsyncVideoSource(source);
            videoSourcePlayer.Start();
        }

        private void CloseVideoSource() 
        {
            this.Cursor = Cursors.WaitCursor;

            // stop current video source
            
            videoSourcePlayer.SignalToStop();
            video.SignalToStop();
            // wait 2 seconds until camera stops
            for (int i = 0; (i < 10) && (videoSourcePlayer.IsRunning); i++)
            {
                Thread.Sleep(100);
            }
            //if (videoSourcePlayer.IsRunning)
                videoSourcePlayer.Stop();
            //if (video.IsRunning)
                video.Stop();
            videoSourcePlayer.BorderColor = Color.Black;
            this.Cursor = Cursors.Default;
        }

        private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            ProcessImage(image);
        }

        public void ProcessImage(Bitmap bm)
        {
            unsafe
            {
                //miért?? http://www.bobpowell.net/lockingbits.htm
                BitmapData bmd = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly, bm.PixelFormat);
                int PixelSize = 3;
                int x_osszeg = 0;
                int x_db = 1;
                int y_osszeg = 0;
                int y_db = 1;
                for (int y = 0; y < bmd.Height; y++)
                {
                    //miért?? http://www.bobpowell.net/lockingbits.htm
                    byte* row = (byte*)bmd.Scan0 + (y * bmd.Stride);

                    for (int x = 0; x < bmd.Width; x++)
                    {
                        //miért?? http://www.bobpowell.net/lockingbits.htm
                        Color c = Color.FromArgb(row[x * PixelSize + 2], row[x * PixelSize + 1], row[x * PixelSize]);
                        float H = c.GetHue();
                        float S = c.GetSaturation();

                        if (H > Href - 2 & H < Href + 2 & S > Sref - 0.1)
                        {
                            //lőn pirosság
                            row[x * PixelSize] = 0;
                            row[x * PixelSize + 1] = 0;
                            row[x * PixelSize + 2] = 255;
                            x_osszeg += x;
                            x_db++;
                            y_osszeg += y;
                            y_db++;
                        }
                    }
                }
                bm.UnlockBits(bmd);
                koordinata.X = x_osszeg / x_db;
                koordinata.Y = y_osszeg / y_db;
                talalatok = x_db + y_db;
                UpdateText(this, "Text", koordinata.X + "x" + koordinata.Y+", "+talalatok);
            }
        }
        private delegate void UpdateTextDelegate(Control control, string propertyName, object propertyValue);

        public static void UpdateText(Control control, string propertyName, object propertyValue)
        {
            if (control.InvokeRequired)
            {
                control.Invoke(new UpdateTextDelegate(UpdateText), new object[] { control, propertyName, propertyValue });
            }
            else
            {
                control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
            }
        }

        private void videoSourcePlayer_MouseClick(object sender, MouseEventArgs e)
        {
            int x = (int)((e.X / 640.0) * 160.0);
            int y = (int)((e.Y / 480.0) * 120.0);
            Href = videoSourcePlayer.GetCurrentVideoFrame().GetPixel(x, y).GetHue();
            Sref = videoSourcePlayer.GetCurrentVideoFrame().GetPixel(x, y).GetSaturation();
            KeySender.Stop();
            KeySender.Start();
            this.videoSourcePlayer.NewFrame += new AForge.Controls.VideoSourcePlayer.NewFrameHandler(this.videoSourcePlayer1_NewFrame);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseVideoSource();    
        }

        private void sendkey(object sender, EventArgs e)
        {
            int X=koordinata.X;
            int Y=koordinata.Y;
            if (X != 0 & Y != 0 & talalatok > 10)
            {
                if (X < 80 & Y < 60)
                {
                    System.Windows.Forms.SendKeys.Send("{" + Keys.Down.ToString().ToUpper() + "}");
                }
                else if (X > 80 & Y < 60)
                {
                    System.Windows.Forms.SendKeys.Send("{" + Keys.Up.ToString().ToUpper() + "}");
                }

            }
        }
    }
}
